package com.qiniu.uploadtest.controller;

import com.qiniu.http.Response;
import com.qiniu.uploadtest.entity.ResponseM;
import com.qiniu.uploadtest.utils.UploadFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


@RestController
public class UploadController {

    @Autowired
    private UploadFileUtils uploadFileUtils;


    @PostMapping("/upload")
    public ResponseM<String> uploadFile(@RequestParam("file")MultipartFile file){
        if(file.isEmpty()){
            return new ResponseM<String>(404,"fail","上传文件不能为空");
        }

        String originalFileName = file.getOriginalFilename();
        String serverFileName  =
                UUID.randomUUID().toString().replace("-","") +
                originalFileName.substring(originalFileName.lastIndexOf(".")) ;
        try {
            Response response = uploadFileUtils.uploadFile(file.getInputStream(), serverFileName);
            System.out.println(response);
            if(response.statusCode == 200){
                return new ResponseM<String>(200,"success","http://http://qvhr9fdol.hb-bkt.clouddn.com/"+serverFileName);
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        return  new ResponseM<String>(500,"fail","文件上传失败");
    }



}
